/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

FeedViewer = {};

Ext.onReady(function(){
	Ext.get('loading').fadeOut({remove: true});
	Ext.get('header').show(true);	
    Ext.QuickTips.init();

    Ext.state.Manager.setProvider(new Ext.state.SessionProvider({state: Ext.appState}));

    var tpl = Ext.Template.from('preview-tpl', {
        compiled:true,
        getBody : function(v, all){
            return Ext.util.Format.stripScripts(v || all.description);
        }
    });
    FeedViewer.getTemplate = function(){
        return tpl;
    }
	
	var tpliframe = Ext.Template.from('getsource-tpl', {
        compiled:true,
        getBody : function(v, all){
            return Ext.util.Format.stripScripts(v || all.description);
        }
    });
    FeedViewer.getTemplateIframe = function(){
        return tpliframe;
    }

    var feeds = new FeedPanel();
    var mainPanel = new MainPanel();
		var topPanel = new TopMenu();
	
		FeedViewer.getFeedPanel = feeds;
		FeedViewer.getMainPanel = mainPanel;
    feeds.on('feedselect', function(feed){
        mainPanel.loadFeed(feed);
    });
	
	
    
	
    var viewport = new Ext.Viewport({
        layout:'border',
        items:[
            topPanel,
            feeds,
            mainPanel
         ]
    });
	
	
	
	var cp = new Ext.state.CookieProvider();
	var items = Ext.util.JSON.decode(cp.get("feeditems","{}"));
	var count=0;
	for (var i in items) {
		var inactive=true;
		if (count==0) {inactive=false; feeds.hasfavorite=true;}
		feeds.addFeed({
			url:i,
			text: items[i]
		}, inactive, true);
		count++;
	}
	
	var bookmarkId = location.hash;
    if(bookmarkId){
        bookmarkId = bookmarkId.substring(1, bookmarkId.length);
		var params = bookmarkId.split("&");
		var queryStringList = {};
		for(var i=0;i<params.length;i++)
		{
		    var tmp = params[i].split("=");
		    queryStringList[tmp[0]] = unescape(tmp[1]);
		}
		
		if (typeof(queryStringList.feed)!="undefined") {
			var url = queryStringList.feed;
			if (url.length>10) {
				feeds.showFeed(url);
			}
		}
	}
	var selFeed = feeds.loadFeeds();
	
	 /* var topmenu = new Ext.Panel({
		border: false,
		tbar :new Ext.Toolbar({
			border: false,
			style : "background:url(/images/bg.gif); border:0px;float:right;",
			cls: "top-toolbar",
				items: [{
					iconCls: 'favbtn',
					tooltip: 'Добавить в закладки',
					text: "Добавить в закладки",
					handler: bookmark
					},
				'-',
				 {
                iconCls: 'partnerbtn',
				tooltip: 'Добавьте ридер на Ваш сайт и увеличьте популярность Вашей информации.',
				text: "Партнерство",
                handler: function(){ mainPanel.openGetCode(); }
				},
				'-', 
				{
				id : "regbtn",
                iconCls: 'regbtn',
				tooltip: 'Регистрация нового пользователя',
				text: "Регистрация",
                handler: function(btn){
					 if(!this.regwin){
						this.regwin = new UserRegister();
					}else{
						this.regwin.destroy();
						this.regwin = new UserRegister();
					}
					this.regwin.show(btn); 
					//mainPanel.openTabRegister();
					}
				},	
				{
				id : "loginbtn",
                iconCls: 'loginbtn',
				tooltip: 'Вход в систему',
				text: "Войти",
                handler: function(btn){
					if(!this.loginwin){
						this.loginwin = new LoginWindow();
						//this.loginwin.on('validfeed', this.addFeed, this);
					}
					this.loginwin.show(btn);
					}
				}]
			}),
		bodyBorder : false,
		html: '<img src="/images/bg.gif" width="0" height="0" />',
		height: 24,
		style : "background:url(/images/bg.gif); border:0px;float:right;",
		renderTo: Ext.get("lpanel")
	}); 
	FeedViewer.getTopMenu = function(){
        return topmenu;
    }; */
	//checkLogin(); 

});

// This is a custom event handler passed to preview panels so link open in a new windw
FeedViewer.LinkInterceptor = {
    render: function(p){
        p.body.on({
            'mousedown': function(e, t){ // try to intercept the easy way
                t.target = '_blank';
            },
            'click': function(e, t){ // if they tab + enter a link, need to do it old fashioned way
                if(String(t.target).toLowerCase() != '_blank'){
                    e.stopEvent();
                    window.open(t.href);
                }
            },
            delegate:'a'
        });
    },
	success: function(response,options) {
		//FeedViewer.getTopMenu().getTopToolbar().items.get("checking_user").hide();
		try{
			var result  = Ext.util.JSON.decode(response.responseText);
			if (result) {
				FeedViewer.getTopMenu().getTopToolbar().items.get("loginbtn").hide();
				FeedViewer.getTopMenu().getTopToolbar().items.get("regbtn").hide();
				FeedViewer.getTopMenu().getTopToolbar().add({
					id:'welcome', xtype: 'tbtext', text: 'Здравствуйте, <a class="welcome" href="#"><b>'+result.res.username+'</b></a>'
				});
			}else{
				FeedViewer.LinkInterceptor.notLogin()
			}			
		}catch(e) {FeedViewer.LinkInterceptor.notLogin()};
	},
	notLogin: function(response,options) {
		//FeedViewer.getTopMenu().getTopToolbar().items.get("checking_user").hide();
		FeedViewer.getTopMenu().getTopToolbar().items.get("loginbtn").show();
		FeedViewer.getTopMenu().getTopToolbar().items.get("regbtn").show();
		
	},
	onCheck: function() {
		FeedViewer.getTopMenu().getTopToolbar().items.get("loginbtn").hide();
		FeedViewer.getTopMenu().getTopToolbar().items.get("regbtn").hide();
		FeedViewer.getTopMenu().getTopToolbar().add({
			id:'checking_user', xtype: 'tbtext', text: '<img src="/images/wait.gif" align="absmiddle" /> Авторизация'
		});
	}
};

function bookmark()
{
bookmarkurl="http://rssmaster.org.ua"
bookmarktitle="RSS Master - Ваш информационный центр"
if (document.all)
window.external.AddFavorite(bookmarkurl,bookmarktitle)
else if (window.sidebar) // firefox
window.sidebar.addPanel(bookmarktitle, bookmarkurl, "");
}

function checkLogin() {
	//FeedViewer.LinkInterceptor.onCheck();
	Ext.Ajax.request({
            url: 'checkuser.php',
            success: FeedViewer.LinkInterceptor.success,
            failure: FeedViewer.LinkInterceptor.notLogin,
            scope: this
        });
}



